package com.gold.rabbitmqdemo.study4;

import com.gold.rabbitmqdemo.util.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerEmail {
    /** 队列名称*/
    private static final String QUEUE_NAME="test_queue_fanout_email";
    /** 交互机名称 */
    private static final String  EXCHANGE_NAME="test_exchange_fanout";
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtils.getConnection();
        final Channel channel = connection.createChannel();
        //队列声明
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //绑定队列到交换机 转发器
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "");
        channel.basicQos(1);//保证一次只分发一个
        //定义一个消费者
        Consumer consumer=new DefaultConsumer(channel){
            //消息到达 触发这个方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg=new String(body,"utf-8");
                System.out.println("[1] Recv msg:"+msg);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally{
                    System.out.println("[1] done ");
                    //手动确认消息
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            }
        };
        //自动应答 false,需手动确认消息
        boolean autoAck=false;
        channel.basicConsume(QUEUE_NAME,autoAck , consumer);
    }
}
